package com.oristartech.netty.common.handler;

import com.oristartech.netty.common.dispatcher.ChannelSender;
import com.oristartech.netty.common.message.MessageBuilder;
import com.oristartech.netty.common.message.MessageType;
import com.oristartech.netty.common.message.ResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 ** 响应通道处理
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-03-05 15:59
 * @blame Team
 */
@Slf4j
@ChannelHandler.Sharable
public class NettyResponseChannelHandler extends ChannelInboundHandlerAdapter {

    /**
     ** 请求发送对象
     */
    @Resource
    ChannelSender requestSender;

    /**
     ** 读取数据处理，把响应结果设置到对应的ResponseFuture中
     *
     * @param ctx 通道上下文
     * @param msg 读取到的数据
     * @throws Exception 处理过程中存在异常则抛出
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageBuilder messageBuilder = MessageBuilder.of(msg);
        if(messageBuilder.isMessage(MessageType.RESPONSE)){
            // 处理响应消息
            requestSender.received((ResponseMessage) messageBuilder.getMessage());
            log.info("客户端[{}-{}]收到响应：{}", messageBuilder.getMessage().getTenantId(),
                    messageBuilder.getMessage().getCinemaCode(), messageBuilder.getMessage());
            return;
        }
        ctx.fireChannelRead(msg);
    }
}
